<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="教材名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入教材名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="上传时间">
        <el-date-picker
          v-model="startDateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索
        </el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置
        </el-button
        >
      </el-form-item>
    </el-form>


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['exam:add']"
        >新增
        </el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>


    <el-table
      ref="tables"
      v-loading="loading"
      :data="bookList"
    >
      <el-table-column label="ID" align="center" prop="id"/>
      <el-table-column label="教材名称" align="center" prop="name"/>
      <el-table-column label="上传时间" align="center" prop="createTime">
        <template slot-scope="scope">
              <span>{{
                  parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}')
                }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-row>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDel(scope.row)"
              v-hasPermi="['textbook:update']"
            >删除
            </el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleRead(scope.row)"
              v-hasPermi="['textbook:read']"
            >浏览
            </el-button
            >
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 导入 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".pdf, .mp4"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + true"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--          <p>仅允许导入xls、xlsx格式文件。</p>-->
          <!--          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>-->
          <el-form ref="form" :model="upload.data">
            <el-form-item label="教材名称（不填时使用文件名）" prop="name">
              <el-input v-model="upload.data.name" placeholder="请输入教材名称"/>
            </el-form-item>
          </el-form>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="reader.title" :visible.sync="reader.open" :width="innerWidth + 'px' " append-to-body
               top="0 !important"
    >
      <div v-if="reader.type == 0">
        <iframe v-if="!reader.loading" :src="reader.src" frameborder="0" width="100%" :height="innerHeight - 100"
        ></iframe>
      </div>
      <div v-if="reader.type == 1" >
        <el-row>
          <el-col span="3" />
          <el-col span="15">
            <video controls autoplay :src="reader.src" :style="{height: innerHeight - 100 + 'px'}"/>
          </el-col>
        </el-row>
         </div>
      <div v-else style="text-align: center">加载中...</div>
    </el-dialog>

    <el-dialog :title="del.title" :visible.sync="del.open" width="80" append-to-body>
      <span>是否删除 {{ del.bookName }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="del.open = false">取 消</el-button>
        <el-button type="primary" @click="doDel">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listTextbook, addTextBook, updateTextBook, read, delTextBook, info } from '@/api/exam/textbook'
import { isArray } from 'util'
import { getToken } from '@/utils/auth'

export default {
  name: 'Textbook',
  data() {
    let innerHeight = window.innerHeight
    let innerWidth = window.innerWidth
    return {
      queryParams: {
        name: null,

        pageNo: 1,
        pageSize: 10
      },
      innerHeight: innerHeight,
      innerWidth: innerWidth,
      startDateRange: [],

      categoryList: [], //科目分类
      addExamSubjectCategorySelect: null,
      currentExamSubject: null,

      showSearch: true,

      loading: true,
      bookList: null,
      total: 0,

      addTextbookView: false,
      addTitle: '新增考试',
      addTextbookForm: {
        name: null,
        status: null,
        startTime: null,
        endTime: null
      },
      addTextbookFormTime: [],

      updateTextbookView: false,
      updateTitle: '更新考试信息',
      updateTextbookForm: {
        id: null,
        name: null
      },
      updateTextbookFormTime: [],

      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/textbook/upload',
        data: {
          name: null
        }
      },
      reader: {
        open: false,
        loading: false,
        // 弹出层标题（导入）
        title: '',
        src: '',
        type: 0   //0 文本 1视频
      },
      del: {
        open: false,
        title: '删除电子教材',
        bookName: '',
        id: null
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询任务列表 */
    getList() {
      this.loading = true
      if (this.startDateRange.length > 0) {
        // this.addDateRange(this.queryParams, this.startDateRange ,'StartTime');
        this.queryParams.beginStartTime = new Date(this.startDateRange[0]).getTime() / 1000
        this.queryParams.endStartTime = new Date(this.startDateRange[1]).getTime() / 1000
      }
      let param = {...this.queryParams};
      param.pageNo --;
      listTextbook(param).then(
        (response) => {
          this.bookList = response.rows
          this.total = parseInt(response.total)
          this.loading = false
        }
      )
    },

    statusVal(status) {
      for (let s of this.examStatus) {
        if (s.status == status) {
          return s.label
        }
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.startDateRange = []
      this.endDateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },

    /** 详细按钮操作 */
    handleView(row) {
      this.taskNo = row.taskNo
      this.taskView = true
      const taskId = row.taskId
      getTask(taskId).then((response) => {
        this.evaluate = response.data
        this.title = '考核详情'
      })

      //人员信息
      this.getPersonlTaskList()
    },

    handleAdd() {
      this.upload.open = true
    },

    handleImport() {
      this.upload.title = '题目导入'
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('questionBank/question/importTemplate', {}, `题目导入模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.upload.data.id = response.data.id
      updateTextBook(this.upload.data).then(resp => {
        this.$alert('<div style=\'overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;\'>' + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
        this.getList()
      })
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },

    handleRead(row) {
      this.reader.open = true
      this.reader.loading = true
      info(row['id']).then(response => {
        let info = response.data;
        this.reader.type = info.type;
        if(this.reader.type == 0){
          read(row['id']).then(resp => {
            let binaryData = []
            binaryData.push(resp)// res 后台返回的流数据
            let pdfUrl = ''
            pdfUrl = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }))
            this.reader.src = pdfUrl
            this.reader.loading = false
          })
        }else {
          this.reader.src = process.env.VUE_APP_BASE_API + '/textbook/read?id='+ row['id'] +'&Authorization=' + getToken();
        }
      })

      // this.reader.src = process.env.VUE_APP_BASE_API + '/textbook/read?id=' + row['id'];
    },
    /** 修改按钮操作 */
    handleDel(row) {
      this.del.bookName = row.name
      this.del.open = true;
      this.del.id = row.id;
    },
    doDel() {
      delTextBook(this.del.id).then(resp => {
        this.del.bookName = '';
        this.del.open = false;
        this.del.id = null;
        this.getList();
      });
    },
    onAddExamFormTimeChange(val) {
      console.log(val)
      this.addExamForm.startTime = Date.parse(new Date(val[0])) / 1000
      this.addExamForm.endTime = Date.parse(new Date(val[1])) / 1000
    },
    onUpdateExamFormTimeChange(val) {
      this.updateExamForm.startTime = Date.parse(new Date(val[0])) / 1000
      this.updateExamForm.endTime = Date.parse(new Date(val[1])) / 1000
    },
    /** 提交新增*/
    submitAddExamForm() {
      if (!this.checkSubmitData(this.addExamForm, this.addExamFormRules)) {
        return
      }
      addExam(this.addExamForm).then(resp => {
        this.getList()
        this.addExamView = false

      })
    },
    submitUpdateExamForm() {
      if (!this.checkSubmitData(this.updateExamForm, this.addExamFormRules)) {
        return
      }
      updateExam(this.updateExamForm).then(resp => {
        this.getList()
        this.updateExamView = false
      })
    },
    checkSubmitData(data, rules) {
      for (let key in rules) {
        if (rules[key][0] && rules[key][0].required) {
          if (!data[key] || (isArray(data[key]) && data[key].length == 0)) {
            this.$modal.msgError(rules[key][0].message)
            return false
          }
        }
      }
      return true
    }
  }
}
</script>
